package com.xh.controller.login;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xh.config.MyWebConfig;
import com.xh.service.UserService;
import com.xh.utils.Layui;
import com.xh.utils.MD5Location;
import com.xh.vo.LogUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Controller
public class DController {
    @Autowired
    private UserService userService;
    @Autowired
    private DefaultKaptcha captchaProducer;

    @PostMapping("/login")
    public String login(@RequestParam("username") String name,
                        @RequestParam("password") String pwd,
                        @RequestParam("code") String code,
                        Model model, HttpSession session) {

        String md5Pwd = MD5Location.getMd5(pwd);
        LogUser logUser = userService.getLogUser(name, md5Pwd);
        if (code.equals(session.getAttribute("verifyCode"))) {
            if (logUser != null) {
                session.setAttribute("user", name);
                session.setAttribute("id", logUser.getId());
                session.setAttribute("headPath",logUser.getHeadPath());
                MyWebConfig.getHeadPath(session);
                return "redirect:blog/blogadmin";
            } else {
                model.addAttribute("errMsg", "用户名或密码错误！");
                return "blog/login";
            }
        } else {
            model.addAttribute("errMsg", "验证码错误！");
            return "blog/login";
        }
    }

    @GetMapping("/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaOutputStream = null;
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String verifyCode = captchaProducer.createText();
            httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);
            BufferedImage challenge = captchaProducer.createImage(verifyCode);
            ImageIO.write(challenge, "jpg", imgOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        captchaOutputStream = imgOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @GetMapping("/logout")
    public String logOut(HttpSession session) {
        session.invalidate();
        return "redirect:blog/index";
    }

    @GetMapping("/queryName")
    @ResponseBody
    public String queryName(@RequestParam("name") String name,HttpSession session) {
        LogUser loginUser = userService.getLoginUserByName(name);
        session.removeAttribute("errMsg");
        if (loginUser != null) {
            session.setAttribute("errMsg", "该用户名已存在 !");
            return "true";
        }else {
            return "false";
        }
    }

    @PostMapping("updateHead")
    @ResponseBody
    public Object updateHead(@RequestParam("file") MultipartFile file,HttpSession session) throws IOException {
        String filePath = "C:\\abc\\";
        if (file != null){
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String[] splits = originalFilename.split("\\.");
            UUID uuid = UUID.randomUUID();
            String fileName = uuid+"."+splits[1];
            File file1 = new File(filePath+fileName);
            if (!file1.exists()){
                file1.mkdirs();
            }
            file.transferTo(file1);
            List<String> list = new ArrayList<>();
            list.add(file1.getPath());
            userService.updateHead(fileName, (Integer) session.getAttribute("id"));//877610f4-047a-4d17-813d-45b7dc41f47f.jpg
            return Layui.data(0,list);
        }
        return "err";
    }


}